package LastFM::API;

use 5.008008;
use strict;
use warnings;
use XML::Simple;
use LWP::Simple;
use Data::Dumper;
use Audio::Scan;
use Smart::Comments;
use File::Find;
use File::Basename;
require Exporter;

our @ISA = qw(Exporter);

# Items to export into callers namespace by default. Note: do not export
# names by default without a very good reason. Use EXPORT_OK instead.
# Do not simply export all your public functions/methods/constants.

# This allows declaration	use LastFM::API ':all';
# If you do not need this, moving things directly into @EXPORT or @EXPORT_OK
# will save memory.
our %EXPORT_TAGS = ( 'all' => [ qw(
) ] );


our @EXPORT = qw(
getTagDatabase
getArtists
getAlbums
inLibrary
web_name
get_cover_art_url
getTopTracks
save_url
);

our $VERSION = '0.01';
my $api="http://ws.audioscrobbler.com/2.0/";
my $api_key="2b03aabb866de4bb127bfc32ea6f9501";
my $api_secret="258c2aeb8f5c58e50f49d369a39e40d5";
my $sleep=1;

# Preloaded methods go here.
sub getArtists {
# return a reference to an array of Artist Names
  my $db = $_[0];
  my @files = keys %{$db};
  my %artists;
  map {$artists{$$db{$_}{"TPE1"}}++} @files;
  my @artists= sort keys %artists;
  return \@artists;
}

sub getAlbums {
  # Returns a hash of {artits}{album}
  my $db=$_[0];
  my %albums;
  map {$albums{$$db{$_}{"TPE1"}}{$$db{$_}{"TALB"}}=dirname($_)} keys %$db;
  return \%albums;
}

sub get_tracks {
  my $music_dir=$_[0];
  my $artist=$_[1];
  my $album=$_[2];
  opendir(TRACK,"$music_dir/$artist/$album") || die "TRACK: Can not open $music_dir\n";
  my @tracks= grep (!/^(\.|\.\.|.jpg|.jpeg|.bmp|\(live\)|remix)/,readdir(TRACK));
    return \@tracks;
}

sub inLibrary {
#  given a database reference, artist and track check wether it exists in database
  my $db=$_[0];
  my $artist=$_[1];
  my $track=$_[2];
  foreach my $file (keys %$db){
    next unless $$db{$file}{"TPE1"} eq $artist;
    next unless $$db{$file}{"TIT2"} eq $track;
    return($file);
  }
return 0;
}

sub getTagDatabase {
  my $musicDir=$_[0];
  local $ENV{AUDIO_SCAN_NO_ARTWORK} = 1;
  opendir(MUSIC,$musicDir) || die "Can not open $musicDir\n";
  my @artistDirs=grep(!/(\.|\.\.)/,readdir(MUSIC));
  @artistDirs = map {$musicDir."/".$_} @artistDirs;
  our @files;
  my (%dataBase,%allTags);
  find({ wanted => \&findMusicFiles, follow => 1 }, @artistDirs);
  foreach my $file (@files){ ### Processing (% done)
    $file=~s/\"\(\)//g;
    my $tags = Audio::Scan->scan_tags($file);
    my %tags = %$tags;
    foreach my $tag (keys %{$tags{tags}}){
      next unless $tag=~m/(TALB|TIT2|TPE1|TRDC)/;
      my $value= $tags{tags}{$tag};
      $value=~tr/\n\r//d;
      $value= "" if length($value) >=150;
      $dataBase{$file}{$tag} = $value;
      $allTags{$tag}++;
    }
  }
return(\%dataBase,\%allTags);

sub findMusicFiles {
  push(@files,$File::Find::name) if  m/\.(mp3|wma|m4a|wav|flac|ogg)$/;
}

}



sub web_name {
  my $name=$_[0];
  $name=~s/&/%26/g;     #Remove &
  $name=~tr/_//d;       #Remove under scores
  $name=~s/\(bonus disc\)//g;
  $name=~tr/ /+/;
  return $name;
}




sub get_cover_art_url {
  my $artist=web_name($_[0]);
  my $album=web_name($_[1]);
  my $url="$api/?method=album.getinfo&api_key=$api_key&artist=$artist&album=$album";
  my $xml;
  unless ($xml=get($url)){
    print STDERR "$artist  - $album - XML ERROR\n";
    return 0;
  }
  sleep($sleep);
  my $data = XML::Simple::XMLin($xml);
  return 0 unless defined $$data{album};
  return($$data{album}{image}[3]{content});
}

sub getTopTracks {
my $artist=web_name($_[0]);
my $url="$api?method=artist.gettoptracks&artist=$artist&api_key=$api_key";
my $xml;
unless ($xml=get($url)){
    print STDERR "$artist - XML ERROR\n";
    return 0;
  }
sleep($sleep);
my $data = XML::Simple::XMLin($xml);
$data = $$data{toptracks}{track};
#print Dumper($data);
return($data);
}

sub save_url {
  my $url=$_[0];
  my $location=$_[1];
  unless (is_success(getstore($url,$location))){
    print STDERR "Error Saving $url to $location\n";
    return 0;
  }
}



# Autoload methods go after =cut, and are processed by the autosplit program.

__END__
# Below is stub documentation for your module. You'd better edit it!

=head1 NAME

LastFM::API - Perl extension for blah blah blah

=head1 SYNOPSIS

  use LastFM::API;
  blah blah blah

=head1 DESCRIPTION

Stub documentation for LastFM::API, created by h2xs. It looks like the
author of the extension was negligent enough to leave the stub
unedited.

Blah blah blah.

=head2 EXPORT


my ($dataBase,$allTags) = getTagDatabase($musicDir);


=head1 SEE ALSO

Mention other useful documentation such as the documentation of
related modules or operating system documentation (such as man pages
in UNIX), or any relevant external documentation such as RFCs or
standards.

If you have a mailing list set up for your module, mention it here.

If you have a web site set up for your module, mention it here.

=head1 AUTHOR

Stewart MacArthur, E<lt>macart01@apple.comE<gt>

=head1 COPYRIGHT AND LICENSE

Copyright (C) 2009 by Stewart MacArthur

This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself, either Perl version 5.8.8 or,
at your option, any later version of Perl 5 you may have available.


=cut
